#!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
	from qt import *
	from qttable import *
except ImportError, err:
	print "Module Error", u"Module pyqt is not installed."
	sys.exit(1)

import types
import os
import sys

from mm_sql import *
from mm_csv import *
from mm_xml import *
from mm_vcard import *
from filters import *
from string import *

TRUE = 1
FALSE = 0
ICONS = sys.path[0] + "/ico/"

DATA_TYPES = {
			0 : "Mm_MySQL(\"MySQL;;;;;\")",
			1 : "Mm_PgSQL(\"PostgreSQL;;;;;\")",
			2 : "Mm_sqlite(\"sqlite;;;;;\")",
			3 : "Mm_CSV(\"\")",
			4 : "Mm_XML(\"\")",
			5 : "Mm_vCard(\"\")"
			}

codings = (
			"utf8",
			"iso8859-2",
			"cp1250"
			)
#######################################
############ settingDialog ############
#######################################

class settingDialog(QDialog):
	
	STATUS = {"typ": "", 
			"database": "", 
			"user": "", 
			"passw": '', 
			"table": "", 
			"file": "",
			"host": ""}
	FILTERS = [
		 "toLower",
		 "toUpper",
		 "toCapitalize",
		 "toSwapcase",
		 "toTitle"
	]
	
	CURRENT_FILTERS = []
	
	def __init__(self, parent=None, name=None, flag=0):
		QDialog.__init__(self, parent, name, flag)
		
		self.setCaption("Select Datasource")
		self.setFixedSize(450, 330)
		
		self.panels = []
		
		self.loadLeftPanel(self)
		self.loadMainPanels(self)
		
		closeButton = QPushButton(self)
		closeButton.setText("Close")
		self.connect(closeButton, SIGNAL("clicked()"), self.close)
		closeButton.setGeometry(360, 300, 60, 20)
		
		self.lastAction = None
		self.driver = None
		self.tarpath = None
		
	def loadLeftPanel(self, parent):
		
		leftSetPanel = QListBox(parent)
		leftSetPanel.setGeometry(10, 10, 120, 310)

		leftSetPanel.show()
		
		ico1 = QPixmap(ICONS + "abiword.png")
		lbw1 = QListBoxPixmap(leftSetPanel, ico1)
		lbw1.setText("Text")
		
		ico2 = QPixmap(ICONS + "hdd_unmount.png")
		lbw2 = QListBoxPixmap(leftSetPanel, ico2)
		lbw2.setText("DataSource")
		
		self.connect( leftSetPanel, SIGNAL("highlighted(int)"), self.slotSelAction)
		
		ico3 = QPixmap(ICONS + "package_utilities.png")
		lbw3 = QListBoxPixmap(leftSetPanel, ico3)
		lbw3.setText("Settings")
		
		
	def loadMainPanels(self, parent):
		self.createTextSettingPanel(parent)
		self.createDataSettingPanel(parent)
		self.createAppSettingPanel(parent)
		
		
		
	def createTextSettingPanel(self, parent):
		
		self._panel1 = QHBox(parent)
		self._panel1.setGeometry(140, 10, 300, 280)
		self._panel1.setSpacing(5)
		
		self.panels.append(self._panel1)
		
		_filter1 = QListBox(self._panel1)
		_choose_buttons = QVBox(self._panel1)
		_filter2 = QListBox(self._panel1)
		
		_add_button = QPushButton(">>", _choose_buttons)
		_remove_button = QPushButton("<<", _choose_buttons)
		
		for _filter_item in self.FILTERS:
			_filter1.insertItem(_filter_item)
	
	def createDataSettingPanel(self, parent):
		self._panel2 = QHBox(parent)
		self._panel2.setGeometry(140, 10, 300, 280)
		self._panel2.setSpacing(5)
		self._panel2.setMargin(5)

		self.panels.append(self._panel2)
		
		_grp = QButtonGroup(self._panel2, "DataSource types")
		_grp.setTitle("DataSource types")
		_grp.show()
		
		self.names_of_drivers = []
		
		_rb1 = QRadioButton("MySQL", _grp)
		_rb1.setGeometry(20, 20, 70, 20)
		_rb1.show()
		self.names_of_drivers.append(_rb1)
		_rb2 = QRadioButton("PostgreSQL", _grp)
		_rb2.setGeometry(20, 40, 100, 20)
		_rb2.show()
		self.names_of_drivers.append(_rb2)
		_rb3 = QRadioButton("sqlite", _grp)
		_rb3.setGeometry(20, 60, 70, 20)
		_rb3.show()
		self.names_of_drivers.append(_rb3)
		_rb4 = QRadioButton("CSV", _grp)
		_rb4.setGeometry(20, 80, 70, 20)
		_rb4.show()
		self.names_of_drivers.append(_rb4)
		_rb5 = QRadioButton("XML", _grp)
		_rb5.setGeometry(20, 100, 70, 20)
		_rb5.show()
		self.names_of_drivers.append(_rb5)
		_rb6 = QRadioButton("vCard", _grp)
		_rb6.setGeometry(20, 120, 70, 20)
		_rb6.show()
		self.names_of_drivers.append(_rb6)
		
		self._panel2.connect(_grp, SIGNAL("clicked(int)"), self.slotSelDataSrc)
		
		_labels1 = QVBox(self._panel2)
		_labels2 = QVBox(self._panel2)
		_labels2.hide()
		
		self.datasets = []
		self.datasets.append(_labels1)
		self.datasets.append(_labels2)
		
		self.labels = []
		self.edits = []
		
		_hs = QHBox(_labels1)
		
		self.labels.append(QLabel("Host:", _hs))
		self._host = QLineEdit(_labels1)
		self._host.setMaximumHeight(18)
		self._host.setText(self.STATUS["host"])
		self.edits.append(self._host)
		
		sel_sqlite = QPushButton(_hs)
		sel_sqlite.setMaximumWidth(20)
		sel_sqlite.setPixmap(QPixmap(ICONS + "fileopen.png"))
		self.connect(sel_sqlite, SIGNAL("clicked()"), self.slotOpenSqlite)
		self.edits.append(sel_sqlite)
		
		self.labels.append(QLabel("Database (or DB file):", _labels1))
		self._database = QLineEdit(_labels1)
		self._database.setMaximumHeight(18)
		self._database.setText(self.STATUS["database"])
		self.edits.append(self._database)
		
		self.labels.append(QLabel("User:", _labels1))
		self._user = QLineEdit(_labels1)
		self._user.setMaximumHeight(18)
		self._user.setText(self.STATUS["user"])
		self.edits.append(self._user)
		
		self.labels.append(QLabel("Password:", _labels1))
		self._passw = QLineEdit(_labels1)
		self._passw.setEchoMode(QLineEdit.Password)
		self._passw.setMaximumHeight(18)
		self._passw.setText(self.STATUS["passw"])
		self.edits.append(self._passw)
		
		self.labels.append(QLabel("Table:", _labels1))
		self._table = QLineEdit(_labels1)
		self._table.setMaximumHeight(18)
		self._table.setText(self.STATUS["table"])
		self.edits.append(self._table)

		
		QLabel(" ", _labels1)
		self.apply_src1 = QPushButton(_labels1)
		self.apply_src1.setText("Apply")
		self.apply_src1.setMaximumHeight(20)
		self.apply_src1.setEnabled(0)
		self.connect(self.apply_src1, SIGNAL("clicked()"), self.slotSetStatus)
		
		map(lambda x: x.setDisabled(1), self.edits)
		
		_labels2.setSpacing(5)
		
		self.file_label = QLabel(" Here type path\n to your database file\n or click on \"Browse\"\n button and find it:", _labels2)
		self._file = QLineEdit(_labels2)
		self._file.setMaximumHeight(18)
		self._fileBtn = QPushButton(QIconSet(QPixmap(ICONS + "fileopen.png")), "Browse", _labels2)
		#self._fileBtn.setText("Browse")
		#self._fileBtn.setPixmap(QPixmap(ICONS + "crystalsvg/16x16/actions/fileopen.png"))
		self.connect(self._fileBtn, SIGNAL("clicked()"), self.slotFile)
		
		QLabel(" ", _labels2)
		self.apply_src2 = QPushButton(_labels2)
		self.apply_src2.setText("Apply")
		self.apply_src2.setMaximumHeight(20)

		self.connect(self.apply_src2, SIGNAL("clicked()"), self.slotSetStatus)
		
	
	def createAppSettingPanel(self, parent):
		self._panel3 = QVBox(parent)
		self._panel3.setGeometry(140, 10, 300, 280)
		self._panel3.setSpacing(10)
		
		_grp = QButtonGroup(self._panel3, "Select path")
		_grp.setTitle("Select path")
		_tarp = QHBox(_grp)
		_tarp.setSpacing(5)
		_tarp.setGeometry(20,20,200,60)
		
		self._tarpath = QLineEdit(_tarp)
		
		openBtn = QPushButton(_tarp)
		self.connect(openBtn, SIGNAL("clicked()"), self.slotDir)
		
		_grp2 = QButtonGroup(self._panel3, "Encoding")
		_grp2.setTitle("Encoding")
		_tarp2 = QHBox(_grp2)
		_tarp2.setSpacing(5)
		_tarp2.setGeometry(20,20,250,60)
		
		QLabel("Select detasource encoding:", _tarp2)
		
		self.encoding = QComboBox(0, _tarp2, "Encoding")
		
		map(lambda x: self.encoding.insertItem(x), codings)
		
		self.connect(self.encoding, SIGNAL("activated(int)"), self.slotSetEncoding)
		
		self.apply_pref = QPushButton(self._panel3)
		self.apply_pref.setText("Apply")
		self.apply_pref.setEnabled(0)
		self.apply_pref.setGeometry(100,10,70,20)
		self.connect(self.apply_pref, SIGNAL("clicked()"), self.slotSetPreferences)
		
		self.panels.append(self._panel3)
		
	def slotFile(self):
		filename = QFileDialog.getOpenFileName("", "*.csv *.xml *.vcf *.vcard", self, "FileDialog")
		self._file.setText(filename)
		self.apply_src2.setEnabled(1)
		
	def slotDir(self):
		dirname = QFileDialog.getExistingDirectory("", self, "", "DirDialog")
		self._tarpath.setText(dirname)
		self.apply_pref.setEnabled(1)
	
	def slotMoveFilter(self, id):
		pass
	
	
	def slotOpenSqlite(self):
		filename = QFileDialog.getOpenFileName("", "", self, "FileDialog")
		self._database.setText(filename)
		
			
	def slotSelAction(self, id):
		map(lambda x: x.hide(), self.panels)
		self.panels[id].show()

	def slotSelDataSrc(self, id):
		self.driver = eval(DATA_TYPES[id])
		
		self.apply_src1.setEnabled(1)
		
		print "Object <", self.driver, "> was born!"
		print self.driver.get_status()
		self.STATUS["typ"] = str(self.names_of_drivers[id].text())
		
		# zviditelnovani kolonek na nastaveni datovych zdroju
		if id in range(3):
			if self.datasets[0].isHidden():
				self.datasets[0].show()
				self.datasets[1].hide()
			if not self.edits[0].isEnabled():
				map(lambda x: x.setEnabled(1), self.edits)
		else:
			self.datasets[1].show()
			self.datasets[0].hide()
		
		self.emit(PYSIGNAL("sigSetSrcType"), ())

	def slotSetStatus(self):
		self.STATUS["database"] = str(self._database.text())
		self.STATUS["user"] = str(self._user.text())
		self.STATUS["passw"] = str(self._passw.text())
		self.STATUS["table"] = str(self._table.text())
		self.STATUS["host"] = str(self._host.text())
		self.STATUS["file"] = str(self._file.text())
		
		self.apply_src1.setEnabled(0)
		self.apply_src2.setEnabled(0)
		
		self.emit(PYSIGNAL("sigSetting"), ())

	def slotSetPreferences(self):
		self.tarpath = str(self._tarpath.text())
		self.apply_pref.setEnabled(0)
		self.emit(PYSIGNAL("sigPreferences"), ())
		
	def slotSetEncoding(self, id):
		self.current_encoding = codings[id]
		self.apply_pref.setEnabled(1)
		self.emit(PYSIGNAL("sigEncoding"), ())
		
#from qtsql import *

#class sqlDialog(QSqlEditorFactory):
	#def __init__(self):
		#print "CustomSqlEditorFactory.__init__"
		#QSqlEditorFactory.__init__(self)
		
	#def createEditor(self, parent, field):
		#print "createEditor:", parent, field
		#if str(field.name()) == "statusid":
			#return StatusPicker(parent)
		#else:
			#return QSqlEditorFactory.createEditor(parent, field)
		

class sqlDialog(QDialog):
	def __init__(self, parent=None, name=None, flag=0):
		QDialog.__init__(self, parent, name, flag)
		self.query = ""
		
		self.setCaption("SQL Query Editor")
		self.setFixedSize(280, 200)
		
		self.editor = QTextEdit(self, "editor")
		self.editor.setFocus()
		self.editor.setGeometry(5, 5, 270, 150)
		self.editor.show()
		
		okButton = QPushButton(QIconSet(QPixmap(ICONS + "camera_test.png")), "Save", self)
		self.connect(okButton, SIGNAL("clicked()"), self.saveQuery)
		okButton.setGeometry(90, 165, 80, 25)
		
		closeButton = QPushButton(QIconSet(QPixmap(ICONS + "cancel.png")), "Cancel", self)
		self.connect(closeButton, SIGNAL("clicked()"), self.close)
		closeButton.setGeometry(190, 165, 80, 25)
		
	def saveQuery(self):
		self.query = str(self.editor.text())
		print "SQL Query is: ", self.query
		if upper(split(self.query, ' ')[0]) == "SELECT":
			self.emit(PYSIGNAL("sigSqlQuerySelect"), ())
		else:
			self.emit(PYSIGNAL("sigExSqlQuery"), ())
		